<script setup>
  import { ref,reactive,getCurrentInstance } from 'vue'
  import { useRouter } from 'vue-router';
  import { ElMessage  } from 'element-plus'; // 使用 Element Plus 的 message 组件
  import { userStore } from '@/store/index.js'
  import axios from 'axios'
  const refRuleForm = ref(null)
  const validatePass = (rule, value, callback) => {
    //验证密码不为空
    if (ruleForm.checkPass !== '') {
      //调用方法验证密码的验证器
      refRuleForm.value.validateField('checkPass');
    }
    //验证通过
    callback();
  };
  const validatePass2 = (rule, value, callback) => {
    if (value !== ruleForm.password) {
      callback(new Error('两次输入密码不一致!'));
    } else {
      //验证通过
      callback();
    }
  };
  let validateEmail = (rule, value, callback) => {
    if (value === '') {
      callback(new Error('请输入邮箱地址'));
    } else if (!/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/i.test(value)) {
      callback(new Error('请输入正确的邮箱地址'));
    } else {
      callback();
    }
  };
  const router = useRouter()
  const store = userStore();
  const ruleForm = reactive({
    account: '',
    password: '',
    checkPass: '',
    email: '',
    validCode: ''
  })
  const rules=reactive({
    account: [
      {required: true, message: '请输入账号', trigger: 'blur'}
    ],
    password: [
      {required: true, message: '请输入密码', trigger: 'blur'},
      {validator: validatePass}
    ],
    checkPass: [
      {required: true, message: '请再次输入密码', trigger: 'blur'},
      {validator: validatePass2}
    ],
    mobile: [
      {required: true, message: '请输入手机号', trigger: 'blur'},
      {pattern: /^1[34578]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur'}
    ],
    email: [
      {required: true, message: '请输入邮箱地址', trigger: 'blur'},
      {validator: validateEmail}
    ],
    validCode: [
      {required: true, message: '请输入验证码', trigger: 'blur'},
      //最短4个字符，最长4个字符
      {min: 4, max: 4, message: '长度必须是4个字符', trigger: 'blur'}
    ]
  })
  const submitForm = (formName)=>{
    refRuleForm.value.validate((valid) => {
      if (valid) {
        //将注册信息以post方式提交给服务器
        axios.post(`/user/register`,ruleForm).then(res => {
          // 提示登录成功
          ElMessage({
            message:`用户注册成功`,
            type:'success'
          });
          //更新用户登录的信息
          store.updateUser(res.data)
          store.updateLoginStatus(true)
          //本地存储
          localStorage.setItem('user', JSON.stringify(res.data));
          localStorage.setItem("token", res.headers['authorization']);
          //跳转到首页
          router.push('/');
        }).catch(err => {
          ElMessage.error(err.data);
        });
      } else {
        ElMessage.error(`表单验证错误，提交失败！`);
        return false;
      }
    });
  }
  const sendEmail =()=>{
    //调用上面的email验证器，判断邮箱地址
    refRuleForm.value.validateField('email', msg => {
      //msg返回的是错误信息，如果没有错误信息则验证通过
      console.log(msg)
      if (msg) {
        //邮箱地址格式正确才发送邮件
        axios.get(`/user/sendEmail?address=${ruleForm.email}`).then((resp) => {
          let result = resp.data;
          //获取响应的状态码
          if (resp.status === 200) {
            ElMessage.success('验证码已发送到邮箱地址！');
          } else {
            ElMessage.error('邮件发送失败，请稍候重试！');
          }
        }).catch((error) => {
          ElMessage.error(error.response.data);
        });
      }
      isButtonDisabled.value = true
      setTimeout(() => {
        isButtonDisabled.value = false;
      }, 5000);
    })
  }
</script>
<template>
  <div class="login-container">
    <el-card class="register-content">
      <span class="register-title">蜗牛书城：用户注册</span>
      <!-- :rules="rules" 设定校验规则 -->
      <el-form ref="refRuleForm" :model="ruleForm"
               status-icon size="small" :rules="rules" label-width="100px"
               class="demo-ruleForm">
        <el-form-item label="账号名" prop="account">
          <el-input v-model="ruleForm.account"
                    placeholder="请输入用户账号" style="width: 250px;"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="ruleForm.password"
                    placeholder="请输入用户密码"
                    style="width: 250px;"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input type="password" v-model="ruleForm.checkPass"
                    placeholder="请输入确认密码"
                    style="width: 250px;"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="ruleForm.nickname"
                    placeholder="请输入用户昵称" style="width: 250px;"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="ruleForm.realName"
                    placeholder="请输入真实姓名" style="width: 250px;"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input type="mobile" v-model="ruleForm.mobile"
                    placeholder="请输入正确的手机号"
                    style="width: 250px;"></el-input>
        </el-form-item>
        <!-- 查看ElementPlus的Form组件 -->
        <el-form-item prop="email" label="邮箱地址">
          <el-input v-model="ruleForm.email" placeholder="请输入邮箱地址"
                    style="width: 200px; float: left; margin-right: 5px;"></el-input>
          <el-button type="primary" @click="sendEmail"
                     :disabled="isButtonDisabled">发送验证码</el-button>
        </el-form-item>
        <el-form-item prop="validCode" label="验证码">
          <el-input v-model="ruleForm.validCode"
                    placeholder="请输入验证码" style="width: 140px" minlength="4"
                    maxlength="4">
          </el-input>
        </el-form-item>
        <div class="register-submit">
          <el-button type="success" @click="submitForm('ruleForm')" style="width: 150px;"
                     icon="el-icon-user-solid">提交
          </el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>
<style scoped>
  .login-container {
    position: fixed;
    height: 100%;
    width: 100%;
    left: 0;
    background-image: linear-gradient(0, rgb(68, 68, 235), lightblue);
    display: flex;
    /* 水平居中对齐 */
    justify-content: center;
    /* 垂直居中对齐 */
    height: 100%;
  }
  .register-content {
    margin: 10px auto;
    border-radius: 5px;
    padding: 10px;
    width: 480px;
    height: 560px;
  }
  .register-title {
    font-size: 20px;
  }
  .register-submit {
    text-align: center;
  }
</style>